package com.weiqiao.mall.rest;

import com.google.gson.Gson;
import com.mingsoft.util.StringUtil;
import com.mongodb.client.model.Filters;
import com.weiqiao.aop.log.Log;
import com.weiqiao.mall.domain.*;
import com.weiqiao.mall.service.*;
import com.weiqiao.mall.service.vo.CascadeVO;
import com.weiqiao.modules.monitor.service.RedisService;
import com.weiqiao.modules.system.domain.User;
import com.weiqiao.modules.system.service.UserService;
import com.weiqiao.utils.*;
import org.apache.commons.collections4.CollectionUtils;
import org.bson.Document;
import org.bson.conversions.Bson;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Pageable;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;


/**
 * @Description: 宝贝管理控制器
 * @author: xujun
 * @Date: 2019/10/24 17:21
 */
@RestController
@RequestMapping(value = "api")
public class CommodityController {

    @Autowired
    private ISpecificationsService specificationsService;

    @Autowired
    private IProductParameterService productParameterService;

    @Autowired
    private ILabelShelfService labelShelfService;

    @Autowired
    private ICommodityListService commodityListService;

    @Autowired
    private IVarietyService varietyService;

    @Autowired
    private ICommodityLogService commodityLogService;

    @Autowired
    private ICommodityService commodityService;

    @Autowired
    private IConfigService configService;

    @Autowired
    private IShelfService shelfService;

    @Autowired
    private ISupplierService supplierService;

    /**
     * 店铺管理逻辑层
     */
    @Autowired
    private IShopkeeperService shopkeeperBiz;
    /**
     * 运费管理
     */
    @Autowired
    private IFreightService freightBiz;
    /**
     * 注入redisservice层
     */
    @Autowired
    private RedisService redisService;

    /**
     * 登录用户逻辑层
     */
    @Autowired
    private UserService userService;

    @Autowired
    private ICardCommodityService cardCommodityService;

    @Log("新增宝贝规格")
    @PostMapping(value = "/add-specifications")
    public ResponseEntity saveSpecifications(HttpServletRequest request) {
        return specificationsService.saveSpecifications(request);
    }

    @Log("修改宝贝规格")
    @PostMapping(value = "/edit-specifications")
    public ResponseEntity updateSpecifications(HttpServletRequest request) {
        return specificationsService.updateSpecifications(request);
    }

    @Log("删除宝贝规格")
    @GetMapping(value = "/del-specifications/{specs_id}")
    public ResponseEntity deleteSpecifications(@PathVariable String specs_id) {
        return specificationsService.deleteSpecifications(specs_id);
    }

    @Log("查询宝贝规格列表")
    @GetMapping(value = "/specifications")
    public ResponseEntity getSpecsList(HttpServletRequest request, Pageable pageable) {
        return new ResponseEntity(specificationsService.getSpecsList(request, pageable), HttpStatus.OK);
    }

    @Log("宝贝参数页面获取宝贝分类tree")
    @PostMapping(value = "/variety-tree")
    public ResponseEntity getVarietyTreeList(HttpServletRequest request) {
        return new ResponseEntity(varietyService.getVarietyTreeList(request), HttpStatus.OK);
    }

    @Log("查询宝贝参数列表")
    @GetMapping(value = "/product-parameter-list")
    public ResponseEntity getProductParameterList(HttpServletRequest request, Pageable pageable) {
        return new ResponseEntity(productParameterService.getProductParameterDataList(request, pageable), HttpStatus.OK);
    }

    @Log("新增宝贝参数")
    @PostMapping(value = "/add-product-parameter")
    public ResponseEntity saveProductParameter(HttpServletRequest request) {
        return productParameterService.saveProductParameter(request);
    }

    @Log("删除宝贝参数")
    @GetMapping(value = "/del-product-parameter/{parameter_id}")
    public ResponseEntity deleteProductParameter(@PathVariable String parameter_id, HttpServletRequest request) {
        return productParameterService.deleteProductParameter(request, parameter_id);
    }

    @Log("修改宝贝参数")
    @PostMapping(value = "/edit-product-parameter")
    public ResponseEntity updateProductParameter(HttpServletRequest request) {
        return productParameterService.updateProductParameter(request);
    }

    @Log("宝贝标签左侧列表查询")
    @GetMapping(value = "/label-shelf-list")
    public ResponseEntity getLabelShelfList(HttpServletRequest request) {
        return new ResponseEntity(labelShelfService.getLabelShelfData(request), HttpStatus.OK);
    }

    @Log("宝贝标签右侧商品列表查询")
    @GetMapping(value = "/label-shelf-commodity-list")
    public ResponseEntity getLabelShelfCommodity(HttpServletRequest request, Pageable pageable) {
        return new ResponseEntity(commodityService.findCommoditys(request, pageable), HttpStatus.OK);
    }

    @Log("保存左侧宝贝标签")
    @PostMapping(value = "/label-shelf-save")
    public ResponseEntity saveLabelData(HttpServletRequest request) {
        return labelShelfService.saveLabel(request);
    }


    @Log("商品管理列表")
    @GetMapping("/commodity-list")
    public ResponseEntity commodityList(HttpServletRequest request, Pageable pageable) {
        //公司id
        int company_id = MallUtil.getCompanyId(request);
        Document doc = this.getCommoditysFilter(request);
        //查询总记录数
        int total = commodityListService.countCommodity(company_id, doc);
        //商品列表
        List<CommodityEntity> commodityList = commodityListService.findCommoditys(company_id, doc, pageable);
        return new ResponseEntity(PageUtil.toPage(commodityList, total), HttpStatus.OK);
    }

    @Log("获取商品列表分类信息")
    @PostMapping("/get-variety-cascade")
    public ResponseEntity getVarietyList(HttpServletRequest request) {
        //公司id
        int company_id = MallUtil.getCompanyId(request);
        //获取所有二级分类
        List<CascadeVO> secondVarietyList = varietyService.selectSecondVarietyList(company_id);
        return new ResponseEntity(PageUtil.toPage(secondVarietyList, secondVarietyList.size()), HttpStatus.OK);
    }

    @Log("获取转换为适合级联选择器的商品标签集合")
    @PostMapping("/get-label-cascade")
    public ResponseEntity getShelfList(HttpServletRequest request) {
        //公司id
        int company_id = MallUtil.getCompanyId(request);
        List<CascadeVO> list = labelShelfService.getLabelCascadeList(company_id);
        return new ResponseEntity(list, HttpStatus.OK);
    }

    @Log("修改商品销量")
    @RequestMapping("/update-deal-times")
    public ResponseEntity updateDealTimes(HttpServletRequest request) {
        //公司id,商品ids,销量
        int company_id = MallUtil.getCompanyId(request);
        String ids = request.getParameter("commodity_ids");
        String dealTimes = request.getParameter("dealTimes");
        List<String> commodity_Ids = StringUtil.isBlank(ids) ? new ArrayList<>() : Arrays.asList(ids.split(","));
        boolean result = false;
        if (CollectionUtils.isNotEmpty(commodity_Ids) && StringUtil.isInteger(dealTimes)) {
            Bson filter = Filters.and(Filters.in("commodity_id", commodity_Ids), Filters.eq("company_id", company_id));
            Document doc = new Document("deal_times", Integer.valueOf(dealTimes));
            result = commodityListService.updateCommoditys(company_id, filter, doc);
            //商品流水操作添加
            commodity_Ids.forEach((commodity_id) -> {
                CommodityEntity commodityEntity = commodityListService.findCommodityById(commodity_id, company_id);
                commodityLogService.addCommodityLog(company_id, commodityEntity, 1); // 商品操作流水添加
            });
        }
        return new ResponseEntity(result, HttpStatus.OK);
    }

    @Log("商品管理--批量上，下架")
    @RequestMapping("/updown-commoditys")
    public ResponseEntity upDownCommoditys(HttpServletRequest request) {
        //公司id,商品ids,type类型0-上架 1-下架
        int company_id = MallUtil.getCompanyId(request);
        String ids = request.getParameter("commodity_ids");
        String type = request.getParameter("type");
        List<String> commodity_Ids = StringUtil.isBlank(ids) ? new ArrayList<>() : Arrays.asList(ids.split(","));
        boolean result = false;
        if (StringUtil.isInteger(type)) {
            Bson filter = Filters.and(Filters.eq("company_id", company_id), Filters.in("commodity_id", commodity_Ids));
            Document doc = new Document("state", Integer.valueOf(type));
            result = commodityListService.updateCommoditys(company_id, filter, doc);
            commodity_Ids.forEach((commodity_id) -> {
                CommodityEntity commodityEntity = commodityListService.findCommodityById(commodity_id, company_id);
                if ("0".equals(type)) {
                    commodityLogService.addCommodityLog(company_id, commodityEntity, 2); // 商品操作流水添加 - 上架
                } else if ("1".equals(type)) {
                    commodityLogService.addCommodityLog(company_id, commodityEntity, 3); // 商品操作流水添加 - 下架
                }
            });
        }
        return new ResponseEntity(result, HttpStatus.OK);
    }

    @Log("置顶，取消置顶商品")
    @RequestMapping("/top-commoditys")
    public ResponseEntity topCommoditys(HttpServletRequest request) {
        //公司id,商品ids,type类型0-取消置顶 1-置顶
        int company_id = MallUtil.getCompanyId(request);
        String ids = request.getParameter("commodity_ids");
        String type = request.getParameter("type");
        List<String> commodity_Ids = StringUtil.isBlank(ids) ? new ArrayList<>() : Arrays.asList(ids.split(","));
        boolean result = false;
        if (StringUtil.isInteger(type)) {
            Bson filter = Filters.and(Filters.eq("company_id", company_id), Filters.in("commodity_id", commodity_Ids));
            Document doc = new Document("is_top", Integer.valueOf(type));
            if (type.equals(1)) {
                doc.append("top_time", String.valueOf(System.currentTimeMillis()));
            }
            result = commodityListService.updateCommoditys(company_id, filter, doc);
            commodity_Ids.forEach((commodity_id) -> {
                CommodityEntity commodityEntity = commodityListService.findCommodityById(commodity_id, company_id);
                if ("0".equals(type)) {
                    commodityLogService.addCommodityLog(company_id, commodityEntity, 18); // 商品操作流水添加 - 取消置顶
                } else if ("1".equals(type)) {
                    commodityLogService.addCommodityLog(company_id, commodityEntity, 4); // 商品操作流水添加 - 置顶
                }
            });
        }
        return new ResponseEntity(result, HttpStatus.OK);
    }

    @Log("导出商品列表")
    @PostMapping("/export-commodity-excel")
    public void exportCommodityExcel(HttpServletRequest request, HttpServletResponse response) throws IOException {
        int company_id = MallUtil.getCompanyId(request);
        Document doc = this.getCommoditysFilter(request);
        // 表格内容拼装
        List<Map<String, Object>> list = commodityListService.exportCommodityInfo(company_id, doc);
        FileUtil.downloadExcel(list, response);
    }

    @Log("根据商品id删除单个商品")
    @RequestMapping("/del-commodity")
    public ResponseEntity delCommodityOne(HttpServletRequest request) {
        Map map = commodityListService.deleteById(request);
        return new ResponseEntity(map, HttpStatus.OK);
    }

    @Log("生成二维码")
    @RequestMapping("/create-qrcode")
    public ResponseEntity createQrcode(HttpServletRequest request) {
        //公司id
        int company_id = MallUtil.getCompanyId(request);
        WXCompanyConfEntity companyConf = configService.getCompanyConf(company_id);
        Map map = commodityListService.createQrcode(request, companyConf);
        return new ResponseEntity(map, HttpStatus.OK);
    }

    @Log("修改宝贝库存")
    @RequestMapping("/update-inventory")
    public ResponseEntity updateInventory(@RequestBody CommodityEntity commodityEntity) {
        //公司id,商品id,库存数量
        int company_id = commodityEntity.getCompany_id();
        String commodity_id = commodityEntity.getCommodity_id();
        // 更新库存信息
        Document doc = new Document();
        if (CollectionUtils.isNotEmpty(commodityEntity.getSpecification_details())) {
            // 更新规格的库存信息
            List<Document> list = new ArrayList<>();
            Gson gson = new Gson();
            commodityEntity.getSpecification_details().forEach(info -> {
                list.add(Document.parse(gson.toJson(info)));
            });
            doc.append("specification_details", list);
            // 更改总库存。总库存等于规格总库存之和
            Integer inventory = commodityEntity.getSpecification_details().stream()
                    .mapToInt(CommodityEntity.SpecificationDetails::getInventory).sum();
            commodityEntity.setInventory(inventory);
        }
        doc.append("inventory", commodityEntity.getInventory());
        // 查询条件
        Bson bson = Filters.and(Filters.eq("company_id", company_id), Filters.eq("commodity_id", commodity_id));
        boolean result = commodityListService.updateState(company_id, bson, doc);
        // 更新失败直接返回
        if (!result) {
            return new ResponseEntity(result, HttpStatus.OK);
        }
        // 删除Redis中存储的库存数据
        this.updateRedisInventory(commodityEntity);
        return new ResponseEntity(result, HttpStatus.OK);
    }

    /**
     * 更新Redis中库存
     * @param entity
     */
    private void updateRedisInventory(CommodityEntity entity) {
        // 修改库存成功后，要重新改变缓存里库存
        redisService.hdelete("commodity_inventory" + entity.getCompany_id(), entity.getCommodity_id());
        // 更新规格明细的库存
        if (CollectionUtils.isNotEmpty(entity.getSpecification_details())) {
            for (CommodityEntity.SpecificationDetails info : entity.getSpecification_details()) {
                String purchase_key = info.getFirst_class_id() + info.getTwo_class_id()
                        + info.getThree_class_id();
                redisService.hdelete("commodity_specification_inventory" + entity.getCompany_id(), purchase_key);
            }
        }
    }

    @Log("修改宝贝标签")
    @RequestMapping("/update-commodity-label")
    public ResponseEntity updateCommodityLabel(HttpServletRequest request) {
        //公司id
        int companyId = MallUtil.getCompanyId(request);
        // 需要修改的商品集合，传来的是字串，需要转为集合
        String ids = request.getParameter("commodity_ids");
        List<String> commodity_Ids = StringUtil.isBlank(ids) ? new ArrayList<>() : Arrays.asList(ids.split(","));
        // 更改的标签集合，传来的是字串，需要转为集合
        String label = request.getParameter("labels");
        List<String> labels = StringUtil.isBlank(label) ? new ArrayList<>() : Arrays.asList(label.split(","));
        // 查询条件，公司id，需要修改的商品。更改内容为商品标签集合
        Bson filter = Filters.and(Filters.eq("company_id", companyId), Filters.in("commodity_id", commodity_Ids));
        boolean result = commodityListService.updateCommoditys(companyId, filter, new Document("label_brand_ids", labels));
        return new ResponseEntity(result, HttpStatus.OK);
    }

    // （此处因注入用了多个service，所以没有把具体逻辑放入service层中）
    @Log("复制单个商品信息")
    @RequestMapping("/copy-commodity")
    public ResponseEntity copyCommodity(HttpServletRequest request) {
        //公司id
        int company_id = MallUtil.getCompanyId(request);
        //商品id
        String commodity_id = request.getParameter("commodity_id");
        CommodityEntity commodity = commodityListService.findCommodityById(commodity_id, company_id);
        CommodityEntity commodityEntity = new CommodityEntity();
        boolean result = false;
        if (commodity != null && !StringUtils.isBlank(commodity.getCommodity_id())) {
            commodityEntity = commodity;
            commodityEntity.setCommodity_id(String.valueOf(System.currentTimeMillis()));
            commodityEntity.setCreate_date(String.valueOf(System.currentTimeMillis()));
            commodityEntity.setName(commodity.getName() + "（复制）");
            commodityEntity.setDelete_flag(1);
            //复制商品时不复制活动
            commodityEntity.setActive_id("");
            result = commodityListService.addCommodity(commodity);
        }
        Map resultMap = new HashMap();
        resultMap.put("content", commodityEntity);
        resultMap.put("result", result);
        return new ResponseEntity(resultMap, HttpStatus.OK);
    }

    // 商品列表查询条件
    private Document getCommoditysFilter(HttpServletRequest request) {
        //公司id，宝贝类型(商品状态)，商品名称，二级分类id，商品状态，创建时间，供应商名称，商品ids
        int company_id = MallUtil.getCompanyId(request);
        String tabId = request.getParameter("tabId");
        String name = request.getParameter("name");
        String variety_id = request.getParameter("variety_id");
        String state = request.getParameter("state");
        String time = request.getParameter("time");
        String supplier_name = request.getParameter("supplier_name");
        String ids = request.getParameter("commodity_ids");
        String phone = request.getParameter("phone");
        String most_spec_str = request.getParameter("most_spec");
        List<String> commodity_Ids = StringUtils.isBlank(ids) ? new ArrayList<>() : Arrays.asList(ids.split(","));
        //查询条件
        Document doc = new Document();
        // 默认筛选条件
        if ("2".equals(tabId)) {
            doc.append("state", 0);
        } else if ("3".equals(tabId)) {
            doc.append("state", 1);
        }
        if (CollectionUtils.isNotEmpty(commodity_Ids)) {
            //导出勾选时获取勾选的商品ids
            doc.append("commodity_id", new Document("$in", commodity_Ids));
            return doc;
        }
        if (!StringUtil.isBlank(name)) {
            doc.append("name", new Document("$regex", name));
        }
        if (!StringUtil.isBlank(variety_id)) {
            String[] varietyIdList = variety_id.split(",");
            doc.append("variety_id", varietyIdList[0]);
            if (varietyIdList.length > 1) doc.append("second_variety_id", varietyIdList[1]);
        }
        // 状态筛选
        if (!StringUtil.isBlank(state)) {
            doc.append("state", Integer.parseInt(state));
        }
        if (!StringUtil.isBlank(supplier_name)) {
            doc.append("supplier_name", new Document("$regex", supplier_name));
        }
        if (!StringUtil.isBlank(time) && time.split("~").length > 1) {
            try {
                String start = time.split("~")[0];
                String end = time.split("~")[1];
                Date startdate = new SimpleDateFormat("yyyy-MM-dd HH:mm").parse(start);
                Date enddate = new SimpleDateFormat("yyyy-MM-dd HH:mm").parse(end);
                if (start.equals(end)) {
                    enddate = new SimpleDateFormat("yyyy-MM-dd HH:mm").parse(DateUtil.getTomdayDate(new Date()));
                }
                doc.append("create_date", new Document("$gte", String.valueOf(startdate.getTime())).append("$lte",
                        String.valueOf(enddate.getTime())));
            } catch (ParseException e) {
                e.printStackTrace();
            }
        }
        if (StringUtils.isNotBlank(phone)) {
            // 电话号不为空时,需要找到该用户的id。通过用户id去供应商表查找到供应商的id，然后在去查找供应商的商品
            // 注：这里的供应商只是一个部门，公司内部的供应商。S2B2C的供应商是公司
            User user = userService.findByPhoneAndCompanyId(phone, company_id);
            Bson filter = new Document("user_list", String.valueOf(user.getId()));
            SupplierEntity entity = supplierService.findSupplierInfo(company_id, filter);
            doc.append("supplier_id", entity.getSupplier_id());
        }
        if (StringUtil.isInteger(most_spec_str)) {
            int most_spec = Integer.parseInt(most_spec_str);
            doc.append("specification_details.1", new Document("$exists", most_spec));
        }
        doc.append("company_id", company_id);
        doc.append("delete_flag", new Document().append("$ne", 1));
        return doc;
    }

    @Log("商品分类用于下拉选")
    @PostMapping("/variety-lists")
    public ResponseEntity getVarietyLists(HttpServletRequest request) {
        int company_id = MallUtil.getCompanyId(request);
        //获取商品所有分类（包含一级和二级分类）
        List<VarietyEntity> varietyList = varietyService.selectCompanyList(company_id);
        return new ResponseEntity(varietyList, HttpStatus.OK);
    }

    @Log("获取当前分类信息")
    @PostMapping("/get-variety")
    public ResponseEntity getVariety(HttpServletRequest request) {
        String varietyId = request.getParameter("variety_id"); // 公司id
        VarietyEntity varietyList = varietyService.findVarietyById(varietyId);
        return new ResponseEntity(varietyList, HttpStatus.OK);
    }

    // 目的:获取最后一次创建的商品所选择的宝贝分类
    @Log("获取最近一次创建的商品信息")
    @PostMapping("/get-latest-commodity")
    public ResponseEntity getLatestCommodity(HttpServletRequest request) {
        return new ResponseEntity(commodityListService.getLatestCommodity(request), HttpStatus.OK);
    }

    @Log("获取当前商品信息")
    @PostMapping("/get-commodity")
    public ResponseEntity getCommodity(HttpServletRequest request) {
        //公司id
        int company_id = MallUtil.getCompanyId(request);
        String commodity_id = request.getParameter("commodity_id");
        return new ResponseEntity(commodityListService.findCommodityById(commodity_id, company_id), HttpStatus.OK);
    }

    @Log("获取当前分类的宝贝参数")
    @PostMapping("/get-product-parameter-list")
    public ResponseEntity getProductParameterList(HttpServletRequest request) {
        return new ResponseEntity(productParameterService.getProductParameter(request), HttpStatus.OK);
    }

    @Log("获取当前公司所有的宝贝规格")
    @PostMapping("/get-specifications-list")
    public ResponseEntity getSpecificationsList(HttpServletRequest request) {
        return new ResponseEntity(specificationsService.getSpecificationsList(request), HttpStatus.OK);
    }

    @Log("获取当前公司的所有运费模板")
    @PostMapping("/get-freight-list")
    public ResponseEntity getFreightList(HttpServletRequest request) {
        int company_id = Integer.parseInt(request.getParameter("company_id"));
        Bson filter = Filters.and(Filters.eq("company_id", company_id), Filters.eq("is_del", 0));
        return new ResponseEntity(freightBiz.findFreightByBson(company_id, filter), HttpStatus.OK);
    }

    @Log("商品管理--添加商品")
    @RequestMapping("/add-commodity")
    public ResponseEntity addCommodity(@RequestBody CommodityEntity commodityEntity) {
        // 公司id
        int company_id = commodityEntity.getCompany_id();
        boolean is_insert = false;
        if (StringUtil.isBlank(commodityEntity.getCommodity_id())) {
            commodityEntity.setCommodity_id(String.valueOf(System.currentTimeMillis()));
        }
        CommodityEntity c = commodityListService.findCommodityById(commodityEntity.getCommodity_id(), company_id);
        if (c == null) {
            c = new CommodityEntity();
            is_insert = true;
        }
        commodityEntity.setCreate_date(commodityEntity.getCommodity_id());
        commodityEntity.setCompany_id(company_id);
        commodityEntity.setDeal_times(c.getDeal_times());
        commodityEntity.setComments(c.getComments());
        commodityEntity.setComment_times(c.getComment_times());
        commodityEntity.setApp_comment(c.getApp_comment());
        commodityEntity.setApp_times(c.getApp_times());
        commodityEntity.setComment_state(c.getComment_state());
        commodityEntity.setLook_number(c.getLook_number());
//        commodityEntity.setState(c.getState());
        commodityEntity.setHasNotice(c.getHasNotice());
        commodityEntity.setSpike_price(c.getSpike_price());
        commodityEntity.setActive_id(c.getActive_id());
        //设置商品未删除状态（复制商品时状态是已删除，保存商品信息时放开）
        commodityEntity.setDelete_flag(0);
        // 当供应商id为空时,供应商id为公司id时 为自营商品
        if (StringUtils.isBlank(commodityEntity.getSupplier_id()) ||
                commodityEntity.getSupplier_id().equals(String.valueOf(commodityEntity.getCompany_id()))) {
            commodityEntity.setIs_supplier(0);
        } else {
            commodityEntity.setIs_supplier(1);
        }
        // 清除被删除的规格明细信息
        this.clearSpecificationDetailForDelete(commodityEntity);
        // 更新商品参数信息,做向下兼容，兼容了props字段，对props进行补充
        updateCommodityParameter(commodityEntity);
        //判断商品名称是否重复
        if (isExists(company_id, commodityEntity)) {
            return new ResponseEntity(false, HttpStatus.OK);
        }
        //标签商品自动加入货架
        if (commodityEntity.getOrigin_tag() != 0) {
            upsertShelf(company_id, commodityEntity);
        }
        commodityListService.addCommodity(commodityEntity);
        if (is_insert) {
            commodityLogService.addCommodityLog(company_id, commodityEntity, 0); // 商品操作流水添加 - 新建商品
        } else {
            commodityLogService.addCommodityLog(company_id, commodityEntity, 5); // 商品操作流水添加 - 修改商品
        }
        return new ResponseEntity(true, HttpStatus.OK);
    }

    /**
     * 清除被删除的规格明细信息
     * @param commodityEntity
     * @return
     */
    private boolean clearSpecificationDetailForDelete(CommodityEntity commodityEntity) {
        // 如果规格列表为空，则清空规格明细
        if (CollectionUtils.isEmpty(commodityEntity.getSpecifications())) {
            commodityEntity.setSpecification_details(new ArrayList<>());
            return true;
        }
        // 如果规格明细为空，则跳过
        if (CollectionUtils.isNotEmpty(commodityEntity.getSpecifications())
                && CollectionUtils.isEmpty(commodityEntity.getSpecification_details())) {
            return false;
        }
        // 存储
        Set<String> spec_ids = new HashSet<>();
        for (CommodityEntity.Specifications specifications : commodityEntity.getSpecifications()) {
            if (org.apache.commons.collections.CollectionUtils.isEmpty(specifications.getValue_list())) {
                continue;
            }
            for (CommodityEntity.Specifications.value value : specifications.getValue_list()) {
                spec_ids.add(value.getKey());
            }
        }
        // 如果规格指为空，则清空规格明细
        if (CollectionUtils.isEmpty(spec_ids)) {
            commodityEntity.setSpecification_details(new ArrayList<>());
            return true;
        }
        for (CommodityEntity.SpecificationDetails specificationDetails : commodityEntity.getSpecification_details()) {
            // 如果规格明细的id值不在规格id集合中，执行规格清空
            if (!StringUtil.isBlank(specificationDetails.getFirst_class_id())
                    && !spec_ids.contains(specificationDetails.getFirst_class_id())) {
                specificationDetails.setFirst_class_id("");
                specificationDetails.setFirst_class_value("");
                specificationDetails.setFirst_class_url("");
            }
            if (!StringUtil.isBlank(specificationDetails.getTwo_class_id())
                    && !spec_ids.contains(specificationDetails.getTwo_class_id())) {
                specificationDetails.setTwo_class_id("");
                specificationDetails.setTwo_class_value("");
            }
            if (!StringUtil.isBlank(specificationDetails.getThree_class_id())
                    && !spec_ids.contains(specificationDetails.getThree_class_id())) {
                specificationDetails.setThree_class_id("");
                specificationDetails.setThree_class_value("");
            }
        }
        return true;
    }

    /**
     * 更新商品参数信息,
     * 兼容以前的商品的参数信息
     *
     * @param e 要更改的信息
     */
    private void updateCommodityParameter(CommodityEntity e) {
        // 新的参数信息对象不为空，则进行覆盖
        if (!StringUtils.isBlank(e.getParameter()) && e.getParameter().size() > 0) {
            Map map = new HashMap();
            e.getParameter().forEach(info -> {
                // 参数名，参数内容
                if (!StringUtils.isBlank(info.getContent())) map.put(info.getParameter_name(), info.getContent());
            });
            e.setProps(map);
        }

    }

    /**
     * 标签商品自动加入货架
     *
     * @param company_id      公司id
     * @param commodityEntity 要更改的信息
     */
    private void upsertShelf(int company_id, CommodityEntity commodityEntity) {
        Bson filter_shelf = Filters.and(Filters.eq("company_id", company_id),
                Filters.eq("shelf_type", 4),
                Filters.eq("shelf_origin_tag", commodityEntity.getOrigin_tag()));
        List<ShelfEntity> shelfEntities = shelfService.getshelfs(filter_shelf);
        if (shelfEntities != null && shelfEntities.size() > 0) {
            for (ShelfEntity shelfEntity : shelfEntities) {
                List<String> commoditys = shelfEntity.getCommoditys();
                if (commoditys != null) {
                    commoditys.add(commodityEntity.getCommodity_id());
                } else {
                    commoditys = new ArrayList<>();
                    commoditys.add(commodityEntity.getCommodity_id());
                }
                shelfEntity.setCommoditys(commoditys);
                Bson filter = Filters.and(Filters.eq("company_id", shelfEntity.getCompany_id()),
                        Filters.eq("shelf_id", shelfEntity.getShelf_id()));
                shelfService.updateShelf(filter, new Gson().toJson(shelfEntity));
            }
        }
    }

    /**
     * 判断商品名是否存在
     *
     * @param company_id
     * @param c
     * @return 存在(true)/不存在（false）
     */
    private boolean isExists(int company_id, CommodityEntity c) {
        Document doc = new Document("company_id", company_id);
        doc.append("name", c.getName());
        doc.append("commodity_id", new Document("$ne", c.getCommodity_id()));
        List<CommodityEntity> list = commodityListService.findCommoditys(company_id, doc);
        return !list.isEmpty() && list.size() > 0 ? true : false;
    }

    @Log("供应商列表用于下拉选")
    @PostMapping("/get-supplier-list")
    public ResponseEntity getSupplierList(HttpServletRequest request) {
        // 公司id
        String companyId = request.getParameter("company_id");
        int company_id = StringUtils.isInteger(companyId) ? Integer.valueOf(companyId) : 0;
        // 查询供应商列表
        List<SupplierEntity> supplierList = supplierService.findAllSupplier(company_id,
                Filters.eq("delete_flag", 0), Filters.eq("create_time", -1));
        return new ResponseEntity(supplierList, HttpStatus.OK);
    }

    @Log("获取商城配置")
    @PostMapping("/get-shop-config")
    public ResponseEntity getShopConfig(HttpServletRequest request) {
        // 公司id
        String companyId = request.getParameter("company_id");
        int company_id = StringUtils.isInteger(companyId) ? Integer.valueOf(companyId) : 0;
        // 获取店铺信息
        Bson filter = Filters.eq("company_id", company_id);
        ShopkeeperEntity shop = shopkeeperBiz.getOneShop(filter);
        return new ResponseEntity(shop, HttpStatus.OK);
    }

    @Log("批量修改商品封面角标图或详情顶部图")
    @PostMapping("/update-tag-img")
    public ResponseEntity updateTagImg(HttpServletRequest request) {
        // 公司id
        int company_id = MallUtil.getCompanyId(request);
        String cover_tag_img = request.getParameter("cover_tag_img");
        String detail_tag_img = request.getParameter("detail_tag_img");
        String commodity_ids_str = request.getParameter("commodity_ids");
        Map<String, Object> resultMap = new HashMap<>();
        String msg = "";
        if (StringUtil.isBlank(commodity_ids_str)) {
            msg = "请选择商品！";
            resultMap.put("result", false);
            resultMap.put("msg", msg);
            return new ResponseEntity(resultMap, HttpStatus.OK);
        }
        List<String> commodity_ids = Arrays.asList(commodity_ids_str.split(","));
        boolean flag = commodityService.updateTagImage(company_id, commodity_ids, cover_tag_img, detail_tag_img);
        if (!flag) {
            msg = "请选择图片！";
        }
        resultMap.put("result", flag);
        resultMap.put("msg", msg);
        return new ResponseEntity(resultMap, HttpStatus.OK);
    }
}
